package com.darren.euc.action;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.darren.euc.entity.*;
import com.darren.euc.service.SpaceService;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.darren.euc.service.ClientService;
import com.darren.euc.service.LoginValidateService;
import com.darren.euc.service.UserService;
import com.darren.euc.util.EncryptAESUtil;
import com.darren.euc.util.JWTUtil;
import com.darren.euc.util.PropertyHelper;
import com.darren.euc.util.SerializeUtil;
import com.darren.euc.util.StringUtil;

import net.sf.json.JSONObject;

@Controller
@RequestMapping("/user")
public class UserAction {
	
	private static final Logger log = Logger.getLogger(UserAction.class);
	
	@Autowired
    private UserService userService;
	
	@Autowired
    private LoginValidateService loginValidateService;

	@Autowired
	private SpaceService spaceService;


	@ResponseBody
    @RequestMapping(value = "/functionusers",method = RequestMethod.POST)
    public List<User> getUserListByFunctionId(@RequestBody JSONObject requestJson,HttpServletRequest request,HttpServletResponse response) {
		User user = (User) request.getAttribute("user");
		if(user == null){
			return new ArrayList<User>();
		}
        String functionId = requestJson.getString("functionId");
		return userService.getUserListByFunctionId(functionId,user.getId());
    }

	@ResponseBody
    @RequestMapping(value = "/user")//,method = RequestMethod.POST)
    public UserVO getUser(HttpServletRequest request,HttpServletResponse response) {
		User user = (User) request.getAttribute("user");
		Space space = spaceService.findByUserId(user.getId());
        return new UserVO(user,space);
    }
	
    @RequestMapping(value = "/register",method = RequestMethod.POST)    
    public String register(User user) {
        userService.save(user);
        return "login";
    }
    
    @RequestMapping(value = "/login")
    public String login(HttpServletRequest request,HttpServletResponse response) {
    	
        return "login";
    }
    
	@ResponseBody
    @RequestMapping(value = "/add",method = RequestMethod.POST)
    public ResponseJSON saveUser(@RequestBody User user,HttpServletRequest request,HttpServletResponse response) {	
		ResponseJSON responseJson = new ResponseJSON();
		try {
			User existsUser = userService.getUserByUserName(user.getUserName());
			if(existsUser != null){
				responseJson.setStatus(-2);
				responseJson.setMessage("用户名已存在！");
			}else{
				existsUser = userService.getUserByUserName(user.getMobile());
				if(existsUser != null){
					responseJson.setStatus(-3);
					responseJson.setMessage("当前手机号已被使用！");
				}else{
					User currentUser = (User) request.getAttribute("user");
					user.setCreateTime(new Date());
					user.setCreatedBy(currentUser.getUserName());
					user.setLastModifyTime(new Date());
					user.setLastModifyBy(currentUser.getUserName());
					String passwordEncryp = EncryptAESUtil.getEncryption(user.getPassword(), PropertyHelper.getEncryptKey());
					user.setPassword(passwordEncryp);
					user = userService.save(user);
					responseJson.setStatus(0);
					responseJson.setMessage("添加成功！");
				}
			}	
		} catch (Exception ex) {
			log.info(ex.getMessage(), ex);
			responseJson.setStatus(-1);
			responseJson.setMessage("添加失败！");
		}
		responseJson.setData(user);
		System.out.println("==============================================================");
		System.out.println(responseJson.toString());
		System.out.println("==============================================================");
		return responseJson;
    }
	
	@ResponseBody
	@RequestMapping(value = "/update", method = RequestMethod.POST)
	public ResponseJSON updateUser(@RequestBody User user, HttpServletRequest request,
			HttpServletResponse response) {
		ResponseJSON responseJson = new ResponseJSON();
		try {
			User currentUser = (User) request.getAttribute("user");
			user.setLastModifyTime(new Date());
			user.setLastModifyBy(currentUser.getUserName());
			
			User userOld = userService.getUserById(user.getId());
			if(userOld != null && userOld.getPassword() != null){
				if(!userOld.getPassword().equals(user.getPassword())){
					String passwordEncryp = EncryptAESUtil.getEncryption(user.getPassword(), PropertyHelper.getEncryptKey());
					user.setPassword(passwordEncryp);
				}
			}
			org.springframework.beans.BeanUtils.copyProperties(user, userOld);
			user = userService.update(userOld);
			responseJson.setStatus(0);
			responseJson.setMessage("保存成功！");
		} catch (Exception ex) {
			log.info(ex.getMessage(), ex);
			responseJson.setStatus(-1);
			responseJson.setMessage("保存失败！");
		}
		responseJson.setData(user);
		System.out.println("==============================================================");
		System.out.println(responseJson.toString());
		System.out.println("==============================================================");
		return responseJson;
	}
	
	@ResponseBody
    @RequestMapping(value = "/query",method = RequestMethod.POST)
    public ResponseJSON queryUser(@RequestBody JSONObject requestJson,HttpServletRequest request,HttpServletResponse response) {	
		ResponseJSON responseJson = new ResponseJSON();
		PageBean pageBean = userService.queryForPageUseHQL(requestJson.getJSONObject("data"), PropertyHelper.getPageSize(), requestJson.getInt("currentPage"));
		responseJson.setData(pageBean);
		return responseJson;
    }
    
    @ResponseBody
    @RequestMapping(value = "/deleteUser",method = RequestMethod.POST)
    public ResponseJSON deleteUser(@RequestBody JSONObject requestJson,HttpServletRequest request,HttpServletResponse response) {
    	ResponseJSON responseJson = new ResponseJSON();
    	JSONObject jsonData = new JSONObject();
    	responseJson.setData(jsonData);    	
    	try{
    		Integer id = Integer.parseInt(requestJson.getString("id"));
    		userService.deleteById(id);
        	responseJson.setStatus(0);
    		responseJson.setMessage("删除成功！");
    	}catch(Exception ex){
    		log.info(ex.getMessage(),ex);
        	responseJson.setStatus(-1);
    		responseJson.setMessage("删除失败！");
    	}
    	System.out.println("==============================================================");
    	System.out.println(requestJson.toString());
    	System.out.println(responseJson.toString());
    	System.out.println("==============================================================");
        return responseJson;
    }
        
    @ResponseBody
    @RequestMapping(value = "/loginValidate",method = RequestMethod.POST)
    public ResponseJSON login(@RequestBody JSONObject requestJson,HttpServletRequest request,HttpServletResponse response) {
    	ResponseJSON responseJson = new ResponseJSON();
    	JSONObject jsonData = new JSONObject();
    	String userName = requestJson.getString("username");
    	String password = requestJson.getString("password");    	
    	if(StringUtil.isEmptyOrWhitespace(userName) || StringUtil.isEmptyOrWhitespace(password)){
    		responseJson.setStatus(1);
    		responseJson.setMessage("用户名或者密码不能为空。");
    	}else{
    		User user = userService.getUserByUserName(userName);
    		password = EncryptAESUtil.getEncryption(password, PropertyHelper.getEncryptKey());
    		if(user == null){
    			responseJson.setStatus(2);
        		responseJson.setMessage("当前用户不存在。");
    		}else if(!password.trim().equals(user.getPassword())){
    			responseJson.setStatus(3);
        		responseJson.setMessage("密码不正确，请核对后再输入。");
    		}else{
    			responseJson.setStatus(0);
        		responseJson.setMessage("登陆成功。");        		
        		LoginValidate loginValidate  = new  LoginValidate();
        		loginValidate.setUserId(user.getId());
        		loginValidate.setLoginTime(new Date());
        		loginValidate.setExpiredTime(Integer.parseInt(PropertyHelper.getAccessTokenExpire()));
        		loginValidate.setRecordStatus("A");
        		try {
					loginValidate.setApplicationSession(new AppSession());
				} catch (IOException e) {
					log.error(e.getMessage(),e);
				}
        		loginValidate = loginValidateService.save(loginValidate);
        		String accessToken = JWTUtil.generateAccessJWT(loginValidate);
        		String refreshToken = JWTUtil.generateRefreshJWT(loginValidate);
        		String expires_in = PropertyHelper.getAccessTokenExpire();
        		
        		AppSession appSession = null;
    			try {
    				appSession = loginValidate.getApplicationSession();
    			} catch (Exception ex) {
    				log.error(ex.getMessage(),ex);
    			}
    			jsonData.put("accessToken", accessToken);
    			jsonData.put("refreshToken", refreshToken);
    			jsonData.put("expiresIn", expires_in);
    			Boolean isBusiManage = userService.IsAdmin(user.getId(),10000);
    			jsonData.put("isBusiManage",isBusiManage);
    			appSession.setAttribute("accessToken", accessToken);
    			appSession.setAttribute("refreshToken", refreshToken);			
    			try {
    				loginValidate.setApplicationSession(appSession);
    				loginValidate.setAppSession(SerializeUtil.serializeObject(appSession));
    			} catch (IOException e) {
    				log.error(e.getMessage(),e);
    			}			
    			response.setHeader("accessToken", accessToken);
    			response.setHeader("refreshToken", refreshToken);
    			response.setHeader("expiresIn", expires_in);
				response.setHeader("isBusiManage",isBusiManage.toString());
    			loginValidate = loginValidateService.update(loginValidate);
    			responseJson.setData(jsonData);
    		}
    	}
    	System.out.println("==============================================================");
    	System.out.println(requestJson.toString());
    	System.out.println(responseJson.toString());
    	System.out.println("==============================================================");
        return responseJson;
    }
}